//微信公众号工具类封装 2024/02/18
import config from '@/utils/config.js';
import request from '@/utils/request.js';

export default {
	checkAndSaveWxMpOpenid(code, url) {
		let ua = navigator.userAgent.toLowerCase();
		if (ua.match(/MicroMessenger/i) != "micromessenger") {
			return
		}
		
		if(code != null && code != undefined){
			request.post("user/bindMpOpenid", {
				code: code
			})
			return
		}
		let currentuUrl = window.location.href
		let wxMpCode = currentuUrl.match(/=(\S*)&state=1#/)
		if (wxMpCode !== null && wxMpCode != undefined) {
			const replaceUrl = 'https://' + window.location.host + '/#' + url +'?code=' + wxMpCode[1] + '&state=1'
			return location.replace(replaceUrl)
		}else{
			request.get("user/hasMpOpenid").then(res => {
				if(res.result){
					return
				}
				let local = encodeURIComponent("https://" + window.location.host + "/#" + url);
				//访问设置的回调地址 redirect_uri，会重定向显示带code参数的地址
				window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + config.wxMpAppId + 
					"&redirect_uri=" + local +
					"&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
			})
		}
	}
}

